import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:portal_website/pages/news.dart';
import 'package:portal_website/pages/two/interlligent_compu_center_page.dart';
import 'package:portal_website/pages/two/scene_applica_center_page.dart';
import 'package:portal_website/portal_controller.dart';
import 'package:portal_website/tool/string_extension.dart';
import 'package:portal_website/system_page.dart';

import 'pages/double_page.dart';
import 'pages/empowerment_platform.dart';
import 'pages/leadership_care.dart';
import 'pages/service_capability.dart';
import 'pages/two/knowlege_center_page.dart';
import 'pages/two/model_center_page.dart';

// 全局常量：严格匹配 Web 端固定尺寸（基于文档视觉比例换算）
const double WEB_FIXED_WIDTH = 1200; // Web 端固定宽度（模拟浏览器居中布局）
const double PADDING_HORIZONTAL = 40; // 全局水平内边距（匹配文档边距）
const TextStyle FONT_WEB_MAIN = TextStyle(
  fontFamily: 'Arial, sans-serif', // Web 原生无衬线字体
  color: Color(0xFF333333),
);
const TextStyle FONT_WEB_TITLE = TextStyle(
  fontFamily: 'Arial, sans-serif',
  color: Color(0xFF333333),
  fontSize: 18,
  fontWeight: FontWeight.bold,
  height: 1.2, // 行高严格匹配 Web 文本默认行高
);
const TextStyle FONT_WEB_SUBTITLE = TextStyle(
  fontFamily: 'Arial, sans-serif',
  color: Color(0xFF666666),
  fontSize: 14,
  height: 1.2,
);
const TextStyle FONT_WEB_SMALL = TextStyle(
  fontFamily: 'Arial, sans-serif',
  color: Color(0xFF999999),
  fontSize: 12,
  height: 1.2,
);
const TextStyle FONT_WEB_LINK = TextStyle(
  fontFamily: 'Arial, sans-serif',
  color: Color(0xFF0066CC),
  // Web 标准链接蓝色
  fontSize: 12,
  height: 1.2,
  decoration: TextDecoration.none,
);

class PortalPage extends StatelessWidget {
  PortalPage({super.key});
  PortalController? controller;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // 顶部导航栏（含系统门户标题、登录/注册）
      // appBar: _buildTopAppBar(),
      // 主体内容（按文档段落顺序排列）
      backgroundColor: Colors.white,
      body: GetBuilder<PortalController>(
          init: PortalController(),
          builder: (logic) {
            controller = logic;
            return SingleChildScrollView(
              child: Column(
                children: [
                  // 示范基地标题与标语（文档6、7）
                  _buildBaseTitleSection(),

                  // 核心服务平台（文档9及13-17）
                  _buildCoreServicePlatform(),
                  // 新闻动态（文档18及21-24）
                  _buildNewsSection(),
                  // 服务能力（文档25-31）
                  _buildServiceCapability(),
                  // 底部信息（文档32-36）
                  _buildFooter(),
                ],
              ),
            );
          }),
    );
  }

  /// 导航菜单项组件
  Widget _buildNavItem(String title, int index) {
    return GestureDetector(
      onTap: () {
        // controller?.headerIndex = index;
        controller?.update();
        if (index == 0) {
          Get.to(PortalPage());
        } else if (index == 1) {
          Get.to(EmpowermentPlatformPage());
        } else if (index == 2) {
          Get.to(NewsPage());
        } else if (index == 3) {
          Get.to(LeaderCarePage());
        } else if (index == 4) {
          Get.to(ServiceCapabilityPage());
        } else if (index == 5) {
          Get.to(DoublePage());
        }
      },
      child: Padding(
        padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 10),
        child: Text(
          title,
          style: TextStyle(
              color: controller?.headerIndex == index
                  ? Colors.indigoAccent
                  : Color(0xFF666666),
              fontSize: 16,
              fontWeight: controller?.headerIndex == index
                  ? FontWeight.bold
                  : FontWeight.w400),
        ),
      ),
    );
  }

  /// 2. 搜索框（对应文档4：搜索...）
  Widget _buildSearchBar() {
    return Container(
      width: 200,
      margin: EdgeInsets.only(right: 20),
      // padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
      color: Colors.white,
      child: TextField(
        decoration: InputDecoration(
          hintText: "搜索...",
          hintStyle: const TextStyle(fontSize: 16, color: Color(0xFF999999)),
          prefixIcon:
              const Icon(Icons.search, color: Color(0xFF999999), size: 22),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(4),
            borderSide: BorderSide(color: Colors.grey, width: 1.0),
          ),
          contentPadding: const EdgeInsets.symmetric(vertical: 8),
          isDense: true,
        ),
      ),
    );
  }

  /// 3. 示范基地标题与标语（对应文档6：基地名称；文档7：标语）
  Widget _buildBaseTitleSection() {
    return Container(
      width: double.infinity,
      // padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 30),
      color: Colors.black,
      height: 600, // 蓝色主色调占位
      child: Stack(
        children: [
          Positioned.fill(
            child: Image.asset(
              "top_bg.jpg".toAssets(),
              fit: BoxFit.contain,
            ),
          ),
          // Padding(
          //   padding: EdgeInsets.only(left: 40, right: 40),
          //   child: Column(
          //     crossAxisAlignment: CrossAxisAlignment.start,
          //     mainAxisAlignment: MainAxisAlignment.center,
          //     children: [
          //       // 基地名称（文档6）
          //       const Text(
          //         "濮阳人工智能创新应用示范基地",
          //         style: TextStyle(
          //             color: Colors.white,
          //             fontSize: 36,
          //             fontWeight: FontWeight.bold),
          //       ),
          //       const SizedBox(height: 12),
          //       // 基地标语（文档7）
          //       const Text(
          //         "打造智能科技创新高地,引领产业数字化转型",
          //         style: TextStyle(color: Colors.white70, fontSize: 22),
          //       ),
          //       SizedBox(
          //         height: 30,
          //       ),
          //       // 了解更多按钮（文档8）
          //       ElevatedButton(
          //         onPressed: () {},
          //         style: ElevatedButton.styleFrom(
          //           backgroundColor: Colors.white,
          //           foregroundColor: const Color(0xFF007AFF),
          //           padding: const EdgeInsets.symmetric(
          //               horizontal: 26, vertical: 18),
          //           shape: RoundedRectangleBorder(
          //               borderRadius: BorderRadius.circular(4)),
          //         ),
          //         child: const Text(
          //           "了解更多",
          //           style: TextStyle(
          //               fontSize: 14,
          //               color: Colors.indigoAccent,
          //               fontWeight: FontWeight.w500),
          //         ),
          //       ),
          //     ],
          //   ),
          // ),
        ],
      ),
    );
  }

  /// 5. 核心服务平台（对应文档9：核心服务平台；13-17：四大核心服务）
  Widget _buildCoreServicePlatform() {
    // 核心服务数据（文档13-17）
    final coreServices = [
      {
        "title": "智算中心",
        "desc": "提供高性能计算资源和智能算力支持",
        "icon": "cjyyzx.jpg",
        "hasDetail": true,
        "tag": 0,
      },
      {
        "title": "知识中枢",
        "desc": "整合行业知识,助力企业创新发展",
        "icon": "zszs.jpg",
        "hasDetail": true,
        "tag": 1,
      },
      {
        "title": "模型中枢",
        "desc": "提供多样化的人工智能模型服务",
        "icon": "mxzs.jpg",
        "hasDetail": true,
        "tag": 2,
      },
      {
        "title": "场景应用中心",
        "desc": "打造多元化的智能应用场景",
        "icon": "zszx.jpg",
        "hasDetail": true,
        "tag": 3,
      },
    ];

    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 24),
      color: Colors.white,
      margin: const EdgeInsets.symmetric(vertical: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          // 核心服务平台标题（文档9）
          _buildCoreServiceTitle("核心服务平台"),

          const SizedBox(height: 16),
          // 四大核心服务网格（2列2行，与文档布局一致）
          GridView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 4, // 2列布局
              crossAxisSpacing: 36, // 列间距
              mainAxisSpacing: 16, // 行间距
              childAspectRatio: 0.7, // 宽高比（确保布局紧凑，与文档一致）
            ),
            itemCount: coreServices.length,
            itemBuilder: (context, index) {
              Map service = coreServices[index];
              return _buildCoreServiceItem(
                title: service["title"] ?? "",
                desc: service["desc"] ?? "",
                icon: service["icon"] ?? "",
                hasDetail: service["hasDetail"] ?? "",
                tag: service["tag"] ?? -1,
              );
            },
          ),
        ],
      ),
    );
  }

  Widget _buildCoreServiceTitle(String title) {
    return Text(
      title,
      style: TextStyle(
          fontSize: 32, color: Color(0xFF333333), fontWeight: FontWeight.bold),
    );
  }

  /// 核心服务子项（含"查看详情"按钮，对应文档13-17的"查看详情"）
  Widget _buildCoreServiceItem(
      {required String title,
      required String desc,
      String icon = "",
      required bool hasDetail,
      int tag = -1}) {
    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.black12.withAlpha(4),
        borderRadius: BorderRadius.circular(10),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Image.asset(icon.toAssets()),
          // 服务名称与描述
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                title,
                style: const TextStyle(
                    fontSize: 22,
                    color: Color(0xFF333333),
                    fontWeight: FontWeight.bold),
              ),
              const SizedBox(height: 4),
              Text(
                desc,
                style: const TextStyle(fontSize: 16, color: Color(0xFF666666)),
                maxLines: 3,
                overflow: TextOverflow.ellipsis,
              ),
            ],
          ),
          // 查看详情按钮（对应文档13-17的"查看详情 ￫"）
          if (hasDetail)
            TextButton(
              onPressed: () {
                if (tag == 0) {
                  Get.to(InterlligentCompuCenterPage());
                } else if (tag == 1) {
                  Get.to(KnowledgeCenterPage());
                } else if (tag == 2) {
                  Get.to(ModelCenterPage());
                } else if (tag == 3) {
                  Get.to(SceneApplicaCenterPage());
                }
              },
              style: TextButton.styleFrom(
                  padding: EdgeInsets.zero, minimumSize: const Size(50, 20)),
              child: const Text(
                "查看详情 ￫",
                style: TextStyle(fontSize: 18, color: Colors.indigoAccent),
              ),
            ),
        ],
      ),
    );
  }

  /// 6. 新闻动态（对应文档18：新闻动态；21-24：三条新闻）
  Widget _buildNewsSection() {
    // 新闻数据（文档21-24）
    final newsList = [
      {
        "url": "new1.jpg",
        "date": "2024-01-15",
        "title": "濮阳市人工智能产业发展研讨会圆满举行",
        "content": "来自全国各地的专家学者齐聚濮阳,共同探讨人工智能产业发展新机遇..."
      },
      {
        "url": "new2.jpg",
        "date": "2024-01-10",
        "title": "示范基地与行业领军企业达成战略合作",
        "content": "基地与多家人工智能领域的龙头企业签署合作协议,共同推进产业发展..."
      },
      {
        "url": "new3.jpg",
        "date": "2024-01-05",
        "title": "2024 人工智能创新应用展览会开幕",
        "content": "展会集中展示了最新的人工智能技术成果和应用案例,吸引众多参观者..."
      },
    ];

    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 24),
      color: Colors.white,
      margin: const EdgeInsets.symmetric(vertical: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          // 新闻动态标题（文档18）
          _buildCoreServiceTitle("新闻动态"),

          const SizedBox(height: 16),
          // 新闻列表（垂直排列，每条新闻含日期、标题、内容、阅读更多）
          Row(
            children: newsList.map((news) {
              return Expanded(
                child: _buildNewsItem(
                  url: news["url"] ?? "",
                  date: news["date"]!,
                  title: news["title"]!,
                  content: news["content"]!,
                ),
              );
            }).toList(),
          ),
        ],
      ),
    );
  }

  /// 新闻子项（对应文档21-24的新闻格式）
  Widget _buildNewsItem(
      {String url = "",
      required String date,
      required String title,
      required String content}) {
    return Container(
      margin: const EdgeInsets.symmetric(vertical: 12, horizontal: 10),
      padding: EdgeInsets.only(bottom: 10),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10),
        border: Border(bottom: BorderSide(color: Color(0xFFEEEEEE))),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          ClipRRect(
              borderRadius: BorderRadius.circular(10),
              child: Image.asset(url.toAssets())),
          Padding(
            padding: EdgeInsets.only(left: 20, right: 20, top: 20, bottom: 10),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 新闻日期
                Container(
                  child: Text(
                    date,
                    style: const TextStyle(
                        fontSize: 16, color: Colors.indigoAccent),
                  ),
                ),
                // 新闻标题与内容
                Text(
                  title,
                  style: const TextStyle(
                      fontSize: 22,
                      color: Color(0xFF333333),
                      fontWeight: FontWeight.bold),
                  maxLines: null,
                  // overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 4),
                Text(
                  content,
                  style:
                      const TextStyle(fontSize: 16, color: Color(0xFF666666)),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
                const SizedBox(height: 4),
                // 阅读更多按钮（对应文档21-24的"阅读更多 ￫"）
                TextButton(
                  onPressed: () {},
                  style: TextButton.styleFrom(
                      padding: EdgeInsets.zero,
                      minimumSize: const Size(60, 20)),
                  child: const Text(
                    "阅读更多 ￫",
                    style: TextStyle(fontSize: 16, color: Colors.indigoAccent),
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  /// 7. 服务能力（对应文档25：服务能力；26-31：六大服务）
  Widget _buildServiceCapability() {
    // 服务能力数据（文档26-31）
    final serviceList = [
      {
        "icon": "service_icon1.jpg",
        "title": "互联网营销",
        "desc": "提供全方位的数字营销解决方案,助力企业拓展市场"
      },
      {
        "icon": "service_icon2.jpg",
        "title": "人才培养",
        "desc": "专业的人才培训体系,打造高素质技术团队"
      },
      {
        "icon": "service_icon3.jpg",
        "title": "网络安全",
        "desc": "全面的网络安全防护,保障数据和系统安全"
      },
      {
        "icon": "service_icon4.jpg",
        "title": "品牌建设",
        "desc": "专业的品牌策划和推广,提升企业形象"
      },
      {
        "icon": "service_icon5.jpg",
        "title": "金融服务",
        "desc": "提供多样化的金融解决方案,助力企业发展"
      },
      {"icon": "service_icon6.jpg", "title": "会务服务", "desc": "专业的会议活动策划和执行服务"},
    ];

    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 24),
      color: Colors.white,
      margin: const EdgeInsets.symmetric(vertical: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          // 服务能力标题（文档25）
          _buildCoreServiceTitle("服务能力"),

          const SizedBox(height: 16),
          // 六大服务网格（3列2行，与文档布局匹配）
          GridView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 3, // 3列布局
              crossAxisSpacing: 36,
              mainAxisSpacing: 12,
              childAspectRatio: 2, // 宽高比（确保文字不换行，与文档一致）
            ),
            itemCount: serviceList.length,
            itemBuilder: (context, index) {
              Map service = serviceList[index];
              return _buildServiceItem(
                icon: service["icon"] ?? "",
                title: service["title"]!,
                desc: service["desc"]!,
              );
            },
          ),
        ],
      ),
    );
  }

  /// 服务能力子项
  Widget _buildServiceItem(
      {String icon = "", required String title, required String desc}) {
    return Container(
      padding: EdgeInsets.only(top: 10, bottom: 10, left: 30, right: 30),
      decoration: BoxDecoration(
        color: Colors.black12.withAlpha(4),
        borderRadius: BorderRadius.circular(10),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            icon.toAssets(),
            width: 40,
            height: 40,
          ),
          SizedBox(
            height: 10,
          ),
          Text(
            title,
            style: const TextStyle(
                fontSize: 20,
                color: Color(0xFF333333),
                fontWeight: FontWeight.bold),
          ),
          const SizedBox(height: 4),
          Text(
            desc,
            textAlign: TextAlign.center,
            style: const TextStyle(fontSize: 16, color: Color(0xFF666666)),
            maxLines: 2,
            overflow: TextOverflow.ellipsis,
          ),
        ],
      ),
    );
  }

  /// 8. 底部信息（对应文档32-36：关于我们、服务支持、友情链接、版权）
  Widget _buildFooter() {
    return Container(
      width: double.infinity,
      padding: const EdgeInsets.symmetric(horizontal: 60, vertical: 24),
      color: const Color(0xFF333333),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          // 底部链接行（关于我们、服务支持、友情链接，文档32-34）
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 关于我们（文档32）
              _buildFooterLinkGroup(
                  title: "关于我们", subLinks: ["基地介绍", "发展历程", "联系方式"]),
              // 服务支持（文档33）
              _buildFooterLinkGroup(
                  title: "服务支持", subLinks: ["技术支持", "帮助中心", "服务条款"]),
              // 友情链接（文档34）
              _buildFooterLinkGroup(
                  title: "友情链接", subLinks: ["濮阳市政府", "科技部", "工信部"]),
              Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  const SizedBox(height: 24),
                  // 关注我们（文档35）
                  const Text(
                    "关注我们",
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 14,
                        fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 12),
                  // 关注图标占位（无图片，用色块表示）
                  Row(
                    children: [
                      _buildFollowIcon(),
                      const SizedBox(width: 12),
                      _buildFollowIcon(),
                      const SizedBox(width: 12),
                      _buildFollowIcon(),
                    ],
                  ),
                ],
              )
            ],
          ),

          const SizedBox(height: 24),
          // 版权信息（文档36）
          const Align(
            alignment: Alignment.center,
            child: Text(
              "© 2024 濮阳人工智能创新应用示范基地. All rights reserved.",
              style: TextStyle(color: Colors.white70, fontSize: 12),
            ),
          ),
        ],
      ),
    );
  }

  /// 底部链接组（含标题与子链接）
  Widget _buildFooterLinkGroup(
      {required String title, required List<String> subLinks}) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          title,
          style: const TextStyle(
              color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),
        ),
        const SizedBox(height: 8),
        ...subLinks.map((link) {
          return Padding(
            padding: const EdgeInsets.symmetric(vertical: 4),
            child: Text(
              link,
              style: const TextStyle(color: Colors.white70, fontSize: 16),
            ),
          );
        })
      ],
    );
  }

  /// 关注图标占位（无图片，用灰色方块表示）
  Widget _buildFollowIcon() {
    return Container(
      width: 24,
      height: 24,
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(4),
        color: Colors.white30,
      ),
    );
  }
}
